package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.VirtualThreadLogger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@RestController
public class VirtualThreadTestController{
    @Anonymous
    @GetMapping("/test")
    public String test(){
        // 记录虚拟线程基本信息
        VirtualThreadLogger.logThreadInfo("HTTP请求处理");

        // 记录线程池状态
        VirtualThreadLogger.logThreadPoolStatus();
        
        return "Hello springdoc.cn - 当前线程：" + Thread.currentThread().getName() + 
               "，是否为虚拟线程：" + Thread.currentThread().isVirtual();
    }
    @Anonymous
    @GetMapping("/test2")
    public String test2(){
        return "Hello springdoc.cn - 当前线程：" + Thread.currentThread().getName() +
                "，是否为虚拟线程：" + Thread.currentThread().isVirtual();
    }
    
    @Anonymous
    @GetMapping("/test/async")
    public String testAsync() {
        long startTime = System.currentTimeMillis();
        
        // 记录开始处理异步请求
        VirtualThreadLogger.logThreadInfo("异步请求处理开始");
        
        try {
            // 创建虚拟线程执行异步任务
            Thread virtualThread = VirtualThreadLogger.createVirtualThread("异步任务", () -> {
                try {
                    // 模拟一些异步处理
                    TimeUnit.MILLISECONDS.sleep(100);
                    System.out.println("异步任务完成，线程：" + Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    VirtualThreadLogger.logError("异步任务", e);
                    Thread.currentThread().interrupt();
                }
            });
            
            // 等待虚拟线程完成
            virtualThread.join();
            
            long endTime = System.currentTimeMillis();
            VirtualThreadLogger.logPerformance("异步请求处理", startTime, endTime);
            
            return "异步任务完成 - 主线程：" + Thread.currentThread().getName() + 
                   "，是否为虚拟线程：" + Thread.currentThread().isVirtual() + 
                   "，处理时间：" + (endTime - startTime) + "ms";
                   
        } catch (Exception e) {
            VirtualThreadLogger.logError("异步请求处理", e);
            return "异步任务失败：" + e.getMessage();
        }
    }
    
    @Anonymous
    @GetMapping("/test/concurrent")
    public String testConcurrent() {
        long startTime = System.currentTimeMillis();
        
        VirtualThreadLogger.logThreadInfo("并发请求处理开始");
        
        try {
            // 创建多个并发的虚拟线程任务
            CompletableFuture<String>[] futures = new CompletableFuture[5];
            
            for (int i = 0; i < 5; i++) {
                final int taskId = i;
                futures[i] = CompletableFuture.supplyAsync(() -> {
                    VirtualThreadLogger.logThreadInfo("并发任务-" + taskId);
                    try {
                        // 模拟不同的处理时间
                        TimeUnit.MILLISECONDS.sleep(50 + taskId * 20);
                        String result = "任务" + taskId + "完成，线程：" + Thread.currentThread().getName();
                        System.out.println(result);
                        return result;
                    } catch (InterruptedException e) {
                        VirtualThreadLogger.logError("并发任务-" + taskId, e);
                        Thread.currentThread().interrupt();
                        return "任务" + taskId + "被中断";
                    }
                });
            }
            
            // 等待所有任务完成
            CompletableFuture.allOf(futures).join();
            
            long endTime = System.currentTimeMillis();
            VirtualThreadLogger.logPerformance("并发请求处理", startTime, endTime);
            
            StringBuilder result = new StringBuilder("所有并发任务完成\n");
            result.append("主线程：").append(Thread.currentThread().getName()).append("\n");
            result.append("是否为虚拟线程：").append(Thread.currentThread().isVirtual()).append("\n");
            result.append("总处理时间：").append(endTime - startTime).append("ms\n");
            
            for (int i = 0; i < futures.length; i++) {
                result.append("任务").append(i).append("结果：").append(futures[i].join()).append("\n");
            }
            
            return result.toString();
            
        } catch (Exception e) {
            VirtualThreadLogger.logError("并发请求处理", e);
            return "并发任务失败：" + e.getMessage();
        }
    }
    
    @Anonymous
    @GetMapping("/test/monitor")
    public String testMonitor() {
        VirtualThreadLogger.logThreadInfo("监控信息查询");
        
        StringBuilder info = new StringBuilder();
        info.append("=== 虚拟线程监控信息 ===\n");
        info.append("当前线程：").append(Thread.currentThread().getName()).append("\n");
        info.append("是否为虚拟线程：").append(VirtualThreadLogger.isCurrentThreadVirtual()).append("\n");
        info.append("请求ID：").append(VirtualThreadLogger.getCurrentRequestId()).append("\n");
        info.append("可用处理器：").append(Runtime.getRuntime().availableProcessors()).append("\n");
        info.append("空闲内存：").append(Runtime.getRuntime().freeMemory() / (1024 * 1024)).append("MB\n");
        info.append("总内存：").append(Runtime.getRuntime().totalMemory() / (1024 * 1024)).append("MB\n");
        
        // 记录线程池状态
        VirtualThreadLogger.logThreadPoolStatus();
        
        return info.toString();
    }
}
